package com.xxja.order.cart.car.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xxja.order.auth.user.pojo.User;

import com.xxja.order.cart.car.mapper.CartMapper;
import com.xxja.order.cart.car.pojo.Cart;
import com.xxja.order.config.interceptor.LoginInterceptor;
import com.xxja.order.utils.PageRequest;
import com.xxja.order.utils.exception.ExceptionCast;
import com.xxja.order.utils.exception.ExceptionCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CartService {

    @Autowired
    private CartMapper cartMapper;

    /**
     * 添加购物车
     * @param cart
     */
    public void addCart(Cart cart) {
        // 获取登录用户
        User user = userIsExist();
        // 查询是否存在
        cart.setUserId(user.getId());
        Long goodId = cart.getGoodId();
        Long num = cart.getNum();
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("good_id", goodId);
        Cart record = cartMapper.selectOne(queryWrapper);
        if (record != null) {
            // 已经取出存在购物车中的数据了
            // 修改购物车数量
            cart.setNum(record.getNum() + num);
        } else {
            // 不存在，新增购物车数据
            cart.setUserId(user.getId());
        }
        this.cartMapper.insert(cart);
    }

    /**
     * 查询购物车中数据
     * @param pageRequest
     * @return
     */
    public IPage<Cart> queryCartList(PageRequest pageRequest) {
        // 判断是否登录
        User user = userIsExist();
        // 查询该用户下是否有商品存在
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id", user.getId());
        Page page = cartMapper.selectPage(pageRequest.setLimit(), queryWrapper);
        return page;
    }

    /**
     * 更新购物车数据
     * @param cart
     */
    public void updateCarts(Cart cart) {
        // 判断是否登录
        User user = userIsExist();
        // 查询是否存在
        Long goodId = cart.getGoodId();
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("good_id", goodId);
        this.cartMapper.update(cart, queryWrapper);
    }

    /**
     * 删除购物车数据
     * @param goodId
     */
    public void deleteCart(String goodId) {
        User user = userIsExist();
        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("good_id", goodId);
        queryWrapper.eq("user_id", user.getId());
        this.cartMapper.delete(queryWrapper);
    }


    /**
     * <p>
     * 校验是不是存在用户,从token中取出用户
     * </p>
     *
     * @return
     */
    private User userIsExist() {
        User user = LoginInterceptor.getLoginUser();
        if (user == null) {
            ExceptionCast.cast(ExceptionCode.USER_NOT_LOGIN);
        }
        return user;
    }


}
